/**
 * API客户端 - 封装所有API调用
 */
class ApiClient {
    constructor() {
        this.baseURL = '';
    }

    /**
 * 通用请求方法
 */
async request(url, options = {}) {
    const config = {
        headers: {
            'Content-Type': 'application/json',
            ...options.headers
        },
        ...options
    };

    try {
        console.log(`Making API request to: ${this.baseURL + url}`);
        const response = await fetch(this.baseURL + url, config);
        console.log(`API response status: ${response.status}`);
        
        if (!response.ok) {
            const errorText = await response.text();
            console.error(`API request failed with status ${response.status}:`, errorText);
            throw new Error(`HTTP ${response.status}: ${errorText}`);
        }
        
        const data = await response.json();
        console.log('API response data:', data);
        return data;
    } catch (error) {
        console.error(`API request failed: ${url}`, error);
        throw error;
    }
}

    /**
     * GET请求
     */
    async get(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        return this.request(fullUrl);
    }

    /**
     * POST请求
     */
    async post(url, data = {}) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    /**
     * PUT请求
     */
    async put(url, data = {}) {
        return this.request(url, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    /**
     * DELETE请求
     */
    async delete(url, params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const fullUrl = queryString ? `${url}?${queryString}` : url;
        return this.request(fullUrl, {
            method: 'DELETE'
        });
    }

    // 索引相关API
    async getIndexStatus() {
        return this.get('/api/v1/index/status');
    }

    async startIndexing(directories, recursive = false, force = false) {
        return this.post('/api/v1/index', {
            directories,
            recursive,
            force
        });
    }

    async clearAllIndex() {
        return this.delete('/api/v1/index/clear');
    }

    async clearDirectoryIndex(directories) {
        return this.post('/api/v1/index/clear/directories', {
            directories
        });
    }

    // 搜索相关API
    async semanticSearch(query, limit, threshold, fileTypes, directories = [], enableDedup = false, dedupMultiplier = 100) {
        return this.post('/api/v1/search/semantic', {
            query,
            limit,
            threshold,
            file_types: fileTypes,
            directories: directories,
            enable_dedup: enableDedup,
            dedup_multiplier: dedupMultiplier
        });
    }

    // 已移除 keywordSearch：传统搜索统一使用 regexSearch

    async regexSearch(query, limit, threshold, fileTypes, pattern, enableDedup = false, dedupMultiplier = 100) {
        return this.post('/api/v1/search/regex', {
            query,
            limit,
            threshold,
            file_types: fileTypes,
            pattern,
            enable_dedup: enableDedup,
            dedup_multiplier: dedupMultiplier
        });
    }

    // 目录管理API
    async getDirectories() {
        return this.get('/api/v1/directories');
    }

    async addDirectory(path) {
        return this.post('/api/v1/directories', { path });
    }

    async removeDirectory(id) {
        return this.delete('/api/v1/directories', { id });
    }

    async toggleDirectoryStatus(id, enabled) {
        return this.put('/api/v1/directories/status', {
            id,
            enabled
        });
    }

    async setIndexDirectories(directories) {
        return this.post('/api/v1/directories/set', {
            directories
        });
    }

    // 系统相关API
    async getSystemStatus() {
        return this.get('/api/v1/system/status');
    }

    async getFileContent(path) {
    // 检查路径是否有效
    if (!path || typeof path !== 'string' || path.trim() === '') {
        console.error('[API Client] Invalid file path:', path);
        throw new Error('Invalid file path');
    }
    
    // 确保路径是字符串并去除首尾空格
    const cleanPath = path.trim();
    
    // 直接构建URL，避免双重编码
    const encodedPath = encodeURIComponent(cleanPath);
    const url = `${this.baseURL}/api/v1/files/content?path=${encodedPath}`;
    console.log('[API Client] Requesting file content from:', url);
    
    return this.request(url)
      .then(response => {
        if (!response.success) {
          throw new Error(response.message || 'Failed to get file content');
        }
        return response.data;
      })
      .catch(error => {
        console.error('[API Client] Error getting file content:', error);
        throw error;
      });
}

    // 配置相关API
    async getConfig() {
        return this.get('/api/v1/config');
    }

    async saveConfig(config) {
        return this.post('/api/v1/config', config);
    }

    // 目录树相关API
    async getDirectoryTree(params = {}) {
        return this.get('/api/v1/directory-tree', params);
    }

    async searchDirectoryTree(data = {}) {
        return this.post('/api/v1/directory-tree/search', data);
    }
}

// 创建全局API客户端实例
window.apiClient = new ApiClient();